/**
 * created by jsq on 2017/10/16
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import {
  Tabs, Button,
  Table, Form,
  Badge, Checkbox,
  Popconfirm, Row,
  Col,
  Dropdown, Menu,
  message, Popover
} from 'antd';
import callbackSettingService from 'containers/setting/callback-setting/callback-setting.service';
import SlideFrame from 'components/slide-frame'
import UpdateCallbackSetting from 'containers/setting/callback-setting/update-callback-setting';
import createApiCallbackSetting from 'containers/setting/callback-setting/create-api-callback-setting';
import 'styles/setting/callback-setting/callback-setting.scss';
import ResizeTable from "components/resize-table";

const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

class CallBackSetting extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      tabsKey: "apiSetting",
      "customizedApi.enable": null,
      data: [],
      columns: [],
      //全局设置
      globalVisible: false,
      globalSetting: {},
      //回调设置
      callbackSetting: {
        title: "",
        showSlideFrame: false, //控制新建回调设置弹出
        values: {}       //回调设置参数
      },
      tabs: [
        {
          key: 'apiSetting',
          name: messages('setting.key146'/*API设置*/)
        },
        {
          key: 'api',
          name: messages('setting.key147'/*API列表*/)
        }
      ],
      pagination: {
        page: 1,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      columnGroup: {
        // api列表
        api: [
          {
            title: "ID",
            key: "id",
            dataIndex: 'id',
            width: '10%'
          },
          {
            title: "API_CODE",
            key: "apiCode",
            dataIndex: 'apiCode'
          },
          {
            title: messages('setting.key148'/*API版本*/),
            key: "apiVersion",
            dataIndex: 'apiVersion',
            width: '10%'
          },
          {
            title: messages('setting.key149'/*API描述*/),
            key: "apiDesc",
            dataIndex: 'apiDesc'
          },
          {
            title: messages('common.column.status'),
            key: "status",
            dataIndex: 'status',
            width: '10%',
            render: recode => (
              <Badge status={recode ? 'success' : 'error'}
                     text={recode ? messages('common.enabled') : messages('common.disabled')}/>
            )
          },
        ],
        //API设置
        apiSetting: [
          {
            //API_CODE
            title: "API_CODE",
            key: "apiCode",
            dataIndex: 'apiCode',
            width: '20%',
            render: desc => <span>{desc ? <Popover placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
          },
          {
            title: messages('setting.key148'/*API版本*/),
            key: "apiVersion",
            dataIndex: 'apiVersion',
            width: '10%',
          },
          {
            title: messages('setting.key150'/*回调地址*/),
            key: "callbackUrl",
            width: '30%',
            dataIndex: 'callbackUrl',
            render: desc => <span>{desc ? <Popover placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
          },
          {
            title: messages('setting.key151'/*系统信息*/),
            key: "layoutPriority",
            dataIndex: 'detail',
            width: '8%',
            render: (desc, record) => {
              let content = <div>
                <div>{messages('setting.key152'/*数据格式*/) + ':'}<span
                  style={{marginLeft: 15}}/>{record.callbackDatatype}</div>
                <div>{messages('setting.key153'/*系统名称*/) + ':'}<span
                  style={{marginLeft: 15}}/>{record.sysName === "" ? '/' : record.sysName}</div>
                <div>{messages('setting.key154'/*管理员名称*/) + ':'}<span
                  style={{marginLeft: 15}}/>{record.sysAdmin === "" ? '/' : record.sysAdmin}</div>
                <div>{messages('setting.key155'/*管理员电话*/) + ':'}<span
                  style={{marginLeft: 15}}/>{record.sysAdminTel === "" ? '/' : record.sysAdminTel}</div>
              </div>;
              return (<Popover content={content}><a> {messages('setting.key156'/*详情*/)}</a></Popover>)
            }
          },
          {
            title: messages('setting.key157'/*获取超链接时间*/),
            key: "connectionRequestTimeout",
            dataIndex: 'connectionRequestTimeout',
            width: '10%'
          },
          {
            title: messages('setting.key158'/*获取超时时间*/),
            key: "connectTimeout",
            dataIndex: 'connectTimeout',
            width: '10%'
          },
          {
            title: messages('common.operation'),
            key: "operation",
            dataIndex: 'operation',
            render: (text, record) => {
              return <a onClick={() => this.handleUpdate(record)}>
                {messages('common.edit')}
              </a>
            }
          }
        ]
      },
    }
  }

  componentDidMount() {
    this.getGlobal();
    this.getIsEnabled();
    this.setState({
      columns: this.state.columnGroup.apiSetting
    }, () => {
      this.getList()
    })
  };

  getIsEnabled() {
    callbackSettingService.getIsEnabled({}).then(response => {
      this.setState({
        "customizedApi.enable": response.data['customizedApi.enable']
      })
    })
  }

  getGlobal() {
    //获取全局设置数据
    let params = {};
    params.companyOid = this.props.company.companyOID;
    callbackSettingService.getGlobalSetting(params)
      .then((response) => {
      let data = response.data
      if(data && data.callbackDatatype){
        this.setState({
          globalSetting: response.data,
        })
      }else {
        //如果没有要给一个默认的
        this.setState({
          globalSetting: {
            "callbackDatatype": "JSON",
            "encodingAeskey": "",
            "encodingToken": "",
            "sysName": "",

            "sysAdmin": "",
            "sysAdminTel": "",
            "connectTimeout": 0,
            "connectionRequestTimeout": 0,
            "companyOid":params.companyOid
          }
        })
      }

    });
  }

  handleMenuClick = (key) => {
    if ((key === 'enabled' && !this.state['customizedApi.enable']) ||
      (key === 'disabled' && this.state['customizedApi.enable'])) {
      callbackSettingService.updateGlobalStatus({"customizedApi.enable": !this.state["customizedApi.enable"]})
        .then(response => {
          this.setState({
            "customizedApi.enable": response.data['customizedApi.enable']
          });
          message.success(`${messages('common.operate.success')}`);
        })
    }
  };

  //点击回调设置
  handleClickItem = (value) => {
    value.callbackDatatype = this.state.globalSetting.callbackDatatype;
    value.companyOid = this.state.globalSetting.companyOid;
    callbackSettingService.getApiSetting({
      companyOid: this.props.company.companyOID,
      page: 1,
      size: 1000
    }).then((response) => {
      let flag = false;
      let apiDetail = {};
      response.data.map((item) => {
        if (parseInt(value.id) === item.apiId) {
          flag = true;
          apiDetail = item;
          apiDetail.apiDetailId = item.id;
        }
      });
      this.setState({
        callbackSetting: {
          title: flag ? messages('setting.key159'/*API回调设置详情*/) :
            messages('setting.key160'/*新建API回调设置*/),
          showSlideFrame: true,
          values: flag ? apiDetail : value
        }
      })
    });
  };

  //获取数据
  getList() {
    this.setState({loading: true});
    let params = {};
    params.page = this.state.pagination.page;
    params.size = this.state.pagination.pageSize;
    let method = null;
    if (this.state.tabsKey === "api") {
      method = callbackSettingService.getApiColumn(params)
    } else {
      params.companyOid = this.props.company.companyOID;
      method = callbackSettingService.getApiSetting(params)
    }
    method.then((response) => {
      response.data.map((item) => {
        item.key = item.id;
      });
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']);
      this.setState({
        loading: false,
        data: response.data,
        pagination
      })
    })
  }

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    let p = this.state.pagination;
    p.page = pagination.current;
    p.pageSize = pagination.pageSize;
    this.setState({
      pagination: p
    }, () => {
      this.getList();
    })
  };

  //Tabs点击
  onChangeTabs = (key) => {
    this.setState({
      pagination: {
        page: 1,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      data: [],
      loading: true,
      page: 0,
      tabsKey: key,
      columns: key === 'api' ? this.state.columnGroup.api : this.state.columnGroup.apiSetting
    }, () => {
      this.getList();
    });
  };

  renderTabs() {
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>
      })
    )
  }
  //全局设置侧滑关闭
  CloseGlobal = () => {
    this.setState({
      globalVisible: false
    });
  };
  //全局设置侧滑关闭
  handleCloseGlobal = () => {
    this.setState({
      globalVisible: false
    },()=>{
      this.getGlobal();
      this.getList();
    });
  };
  //API设置侧滑关闭
  CloseCallback = () => {
    let callbackSetting = {};
    callbackSetting.showSlideFrame = false;
    this.setState({
      callbackSetting
    })
  };
  //API设置侧滑关闭
  handleCloseCallback = () => {
    let callbackSetting = {};
    callbackSetting.showSlideFrame = false;
    this.setState({
      callbackSetting
    },()=>{
      this.getList();
    })
  };

  //点击新建API设置
  handleCreate = () => {
    this.setState({
      callbackSetting: {
        title: messages('setting.key160'/*新建API回调设置*/),
        showSlideFrame: true,
        values: {flag: 'create'}
      }
    })
  };

  //点击编辑API设置
  handleUpdate = (record) => {
    this.setState({
      callbackSetting: {
        title: messages('setting.key161'/*编辑API回调设置*/),
        showSlideFrame: true,
        values: record
      }
    })
  };

  renderTableHeader() {
    return (
      this.state.tabsKey === "api" ?
        <div className="table-header-api">
          <div className="table-header-api-tips">
            {messages('setting.key147'/*API列表*/)}
          </div>
          <div className="table-header-api-title">
            {messages('common.total', {total: `${this.state.pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
        </div>
        :
        <div className="table-header-apiSetting">
          <div className="table-header-apiSetting-tips">
            {messages('setting.key146'/*API设置*/)}
          </div>
          <div className="table-header-apiSetting-title">
            {messages('common.total', {total: `${this.state.pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
          <p>
            <Button type="primary"
                    className="table-header-button"
                    onClick={() => this.handleCreate()}>
              {messages('common.create')}
            </Button>
          </p>
        </div>
    )
  }

  render() {
    const {
      loading,
      pagination,
      globalVisible,
      columns,
      data,
      callbackSetting,
      globalSetting
    } = this.state;
    const {getFieldDecorator} = this.props.form;
    const menu = (
      <Menu>
        <Menu.Item key="enabled">
          <Popconfirm onConfirm={() => this.handleMenuClick("enabled")}
                      title={messages('setting.key162'/*是否确认启用？*/)}>
            <span className="status-options">{messages('common.status.enable')}
              <span className="status-options-icon"/>
            </span>
          </Popconfirm>
        </Menu.Item>
        <Menu.Item key="disabled">
          <Popconfirm onConfirm={() => this.handleMenuClick("disabled")}
                      title={messages('setting.key163'/*是否确认禁用？*/)}>
            <span className="status-options">{messages('common.status.disable')}</span>
          </Popconfirm>
          <div className="status-options-icon"/>
        </Menu.Item>
      </Menu>
    );
    return (
      <div className="call-back-setting">
        <div className="call-back-setting-head">
          <span className="head-context">
            <span className="head-form-title">{messages('setting.key164'/*全局设置*/)}</span>
            <span className="head-form-tips">{messages('setting.key165'/*api未进行设置时，自动应用全局设置*/)}</span>
            <span className="head-status">
              <Dropdown.Button type="primary" overlay={menu}>
                {messages('common.column.status')}：{this.state['customizedApi.enable'] ? messages('common.enabled') : messages('common.disabled')}
              </Dropdown.Button>
            </span>

            <div className="head-form">
               <Form>
                 <Row gutter={24}>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('callbackDatatype')(
                       <div className="formItem-title">
                         <label>{messages('setting.key152'/*数据格式*/)}：</label>
                         <label>{globalSetting.callbackDatatype}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('encodingAeskey')(
                       <div className="formItem-title">
                         <label>encodingAeskey：</label>
                         <label>{globalSetting.encodingAeskey}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                    <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('encodingToken')(
                       <div className="formItem-title">
                         <label>encodingToken：</label>
                         <label>{globalSetting.encodingToken}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>

                 </Row>
                 <Row gutter={24}>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('sysName')(
                       <div className="formItem-title">
                         <label>{messages('setting.key153'/*系统名称*/)}：</label>
                         <label>{globalSetting.sysName}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('sysAdmin')(
                       <div className="formItem-title">
                         <label>{messages('setting.key154'/*管理员名称*/)}：</label>
                         <label>{globalSetting.sysAdmin}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('sysAdminTel')(
                       <div className="formItem-title">
                         <label>{messages('setting.key155'/*管理员电话*/)}：</label>
                         <label>{globalSetting.sysAdminTel}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                 </Row>
                 <Row gutter={24}>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('connectionRequestTimeout')(
                       <div className="formItem-title">
                         <label>{messages('setting.key157'/*获取超链接时间*/)}：</label>
                         <label>{globalSetting.connectionRequestTimeout}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                   <Col span={8}>
                     <FormItem>
                     {getFieldDecorator('connectTimeout')(
                       <div className="formItem-title">
                         <label>{messages('setting.key158'/*获取超时时间*/)}：</label>
                         <label>{globalSetting.connectTimeout}</label>
                       </div>
                     )}
                     </FormItem>
                   </Col>
                 </Row>
                 <Row>
                   <div className="formItem-update">
                     <a onClick={() => this.setState({globalVisible: true})}>
                       {/*修改*/}
                       {messages("common.update")}
                     </a>
                   </div>
                 </Row>
               </Form>
            </div>
          </span>
        </div>
        <div className="call-back-setting-tabs">
          <Tabs onChange={this.onChangeTabs}>
            {this.renderTabs()}
          </Tabs>
        </div>
        <div className="call-back-setting-table-header">
          {this.renderTableHeader()}
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          bordered
        />
        {/*//全局设置*/}
        <SlideFrame title={messages('setting.key164'/*全局设置*/)}
                    show={globalVisible}
                    content={UpdateCallbackSetting}
                    afterClose={this.handleCloseGlobal}
                    onClose={this.CloseGlobal}
                    params={globalSetting}/>
        {/*api设置*/}
        <SlideFrame title={callbackSetting.title}
                    show={callbackSetting.showSlideFrame}
                    content={createApiCallbackSetting}
                    afterClose={this.handleCloseCallback}
                    onClose={this.CloseCallback}
                    params={callbackSetting.values}/>
      </div>
    )
  }
}

CallBackSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedCallBackSetting = Form.create()(CallBackSetting);

export default connect(mapStateToProps)(WrappedCallBackSetting);
